package momo;

import ch.unisi.inf.engine.Image;
import ch.unisi.inf.engine.Library;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;

/**
 * @author bejarj@lu.unisi.ch
 * 		   mohamed.mosa@lu.unisi.ch
 * 
 * This class is responsible for opening our file chooser to add 
 * an image to our image library.
 * 
 */
public final class OpenAction  extends AbstractAction {

	private JFileChooser fc;
	private Library library;
	private Image image;
	private Image[] selectedFiles;
	public OpenAction(){
		putValue(Action.NAME, "Open");
		putValue(Action.MNEMONIC_KEY, KeyEvent.VK_O);
		putValue(Action.SHORT_DESCRIPTION, "Open photo");
	}

	public final void actionPerformed(ActionEvent ev) {
		System.out.println("You have opened a photo");

		fc = new JFileChooser(".");

		fc.setMultiSelectionEnabled(true);

		fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

		//Add a custom  filter "Show All Images"
		fc.addChoosableFileFilter(new ImageFilter());

		//Allow the default filter "All Files" filter
		fc.setAcceptAllFileFilterUsed(true);

		//Add icons based on file types 
		fc.setFileView(new ImageFileIcon());

		//Add the preview pane.
		fc.setAccessory(new ImagePreview(fc));

		int status = fc.showOpenDialog(null);
		if(status == JFileChooser.APPROVE_OPTION){
			File selectedFile = fc.getSelectedFile();
			String path = selectedFile.toString();

			/**for(int i=0, n=selectedFiles.length; i < n; i++){
				System.out.println("Selected: " + selectedFiles[i].getPath()
						+ "/"
						+ selectedFiles[i].getName());

			}*/

			System.out.println("Selected: " + selectedFile);

			library.add( new Image(path, new BufferedImage(image.getColorModel(),image.copyData(null), image.isAlphaPremultiplied(), null)));
			System.out.println(library);
			System.out.println("I added an image");

		}

	}
}
